var CSON, EXROOT, Promise, ROOT, config, userconfig, configCache, configPath, dbg, defaultConfigPath, e, error, error1, error2, fs, log, path, ref, warn;

Promise = require('bluebird');

path = require('path');

fs = require('fs-extra');

const tools = require('./tools')

CSON = require('cson');

ref = require('./utils'), log = ref.log, warn = ref.warn, error = ref.error;

ROOT = global.ROOT, EXROOT = global.EXROOT;

configCache = {};

defaultConfigPath = path.join(ROOT, 'config.cson');

configPath = path.join(EXROOT, 'config.cson');

try {
  fs.accessSync(configPath, fs.R_OK | fs.W_OK);
  userconfig = CSON.parseCSONFile(configPath);
  ref.log("Config loaded from: " + configPath);
} catch (error1) {
  e = error1;
  ref.log(e);
}

try {
  fs.accessSync(defaultConfigPath, fs.R_OK);
  defaultConfig = CSON.parseCSONFile(defaultConfigPath);
  ref.log("Config loaded from: " + defaultConfigPath);
} catch (error2) {
  e = error2;
  ref.log(e);
}

config = tools.extend({},defaultConfig,userconfig);

if (config == null) {
  config = {};
  warn('cannot read config.cson');
}

module.exports = {
  get: function(path, value) {
    var cur, j, len1, p;
    if (configCache[path] != null) {
      return configCache[path];
    }
    path = path.split('.').filter(function(p) {
      return p !== '';
    });
    cur = config;
    for (j = 0, len1 = path.length; j < len1; j++) {
      p = path[j];
      cur = cur != null ? cur[p] : void 0;
    }
    return configCache[path] = cur != null ? cur : value;
  },
  set: function(path, value) {
    console.log(1);
    var cur, error3, i, j, len, len1, p;
    if (configCache[path] != null) {
      delete configCache[path];
    }
    path = path.split('.').filter(function(p) {
      return p !== '';
    });
    cur = config;
    len = path.length;
    for (i = j = 0, len1 = path.length; j < len1; i = ++j) {
      p = path[i];
      if (i !== len - 1) {
        if (typeof cur[p] !== 'object') {
          cur[p] = {};
        }
        cur = cur[p];
      } else {
        cur[p] = value;
      }
    }
    try {
      return fs.writeFileSync(configPath, CSON.stringify(config, null, 2));
    } catch (error3) {
      e = error3;
      return warn(e);
    }
  },
  setDefault: function(path, value) {
    if (!this.get(path)) {
      return this.set(path, value);
    }
  }
};
